const app = getApp();
const api = app.api;
const wxutil = app.wxutil;

Page({
  data: {
    nickName: '',
    signature: '',
    userId: -1,
    gender: 0,
    grade: '',
    profession: '',
    password: '',
    username: '',
    phone: '',
    user: {},
  },

  onLoad() {
    this.getUserDetail();
  },

  /**
   * 获取用户详情
   */
  getUserDetail() {
    const userId = app.globalData.userDetail.id;
    const url = api.userAPI + userId + "/";

    wxutil.request.get(url).then((res) => {
      if (res.data.code == 200) {
        const user = res.data.data;
        this.setData({
          userId: user.id,
          gender: user.gender,
          user: user,
        });
      }
    });
  },

  /**
   * 设置昵称
   */
  setNickName(event) {
    this.setData({
      nickName: event.detail.value,
    });
  },
  setPhone(event) {
    this.setData({
      phone: event.detail.value,
    });
  },

  /**
   * 设置性别
   */
  onChangeGenderTap(event) {
    this.setData({
      gender: event.detail.key,
    });
  },

  /**
   * 设置个性签名
   */
  setGrade(event) {
    this.setData({
      grade: event.detail.value,
    });
  },
  setUserName(event) {
    this.setData({
      username: event.detail.value,
    });
  },
  setPassWord(event) {
    this.setData({
      password: event.detail.value,
    });
  },
  setProfession(event) {
    this.setData({
      profession: event.detail.value,
    });
  },
  setSignature(event) {
    this.setData({
      signature: event.detail.value,
    });
  },

  /**
   * 保存用户信息
   */
  saveInfo() {
    // 获取表单数据
    const nickName = this.data.nickName;
    const signature = this.data.signature;
    const grade = this.data.grade;
    const profession = this.data.profession;
    const username = this.data.username;
    const password = this.data.password;
    const phone = this.data.phone;

    if (!wxutil.isNotNull(nickName)) {
      wx.lin.showMessage({
        type: "error",
        content: "昵称不能为空！",
      });
      return;
    }

    // 构造请求参数
    const url = api.userAPI + "register/";
    const data = {
      username: username,
      password: password,
      nickName: nickName,
      InstituteName: profession,
      phoneNumber: phone,
      position: grade,
      appendix: signature,
    };

    // 更新用户信息
    wxutil.request.post(url, data).then((res) => {
      if (res.data.code == 200) {
        wx.lin.showMessage({
          type: "success",
          content: "注册成功！",
          success() {
            wx.navigateBack();
          },
        });
      } else {
        wx.lin.showMessage({
          type: "error",
          content: "注册失败！",
        });
      }
    });
  },

  onShareAppMessage() {
    return {
      title: "编辑资料",
      path: "/pages/user-edit/index",
    };
  },
});
